<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }}条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/excel')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table
          border
          :data="list"
          :default-sort="{prop: 'timeOfEntry', order: 'ascending'}"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" style="width:100%">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formOfEmploymentFormt (row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态" prop="" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click.native="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="doDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 3, 5, 10]"
            :page-size="sezi"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="hResetFrom"
      >
        <addEmpDialog ref="ref" @success="hSuccess" />
      </el-dialog>
      <!-- 分配权限 -->
      <el-dialog
        :visible.sync="showDialogRole"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <assign-role v-if="showDialogRole" :id="curId" @close="showDialogRole=false" @success="hAssignRoleClose" />
      </el-dialog>
    </div>
  </div>
</template>
<script>

import { getEmployeesList, delEmployee } from '@/api/employees'
import EmployeesEnum from '@/constant/employees'
import addEmpDialog from './empDialog.vue'
import AssignRole from './assignRole.vue'
// console.log(EmployeesEnum.hireType)
// const hireType = {}
// EmployeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
// console.log('hireType', hireType)
const hireType = EmployeesEnum.hireType.reduce((obj, item) => {
  obj[item.id] = item.value
  return obj
}, {})
// console.log('hireType', hireType)

export default {
  name: 'Employees',
  components: { addEmpDialog, AssignRole },
  data() {
    return {
      curId: '',
      showDialogRole: false,
      showDialog: false,
      list: [],
      page: 1,
      sezi: 10,
      total: 0

    }
  },
  created() {
    this.loadEmployeesList()
  },
  methods: {
    hAssignRoleClose() {
      this.showDialogRole = false
      // this.loadEmployeesList()
    },
    // 传id到子组件
    hAssignRole(id) {
      this.showDialogRole = true
      this.curId = id
    },
    // 导出excel
    async  handleDownload() {
      // 1. 发送请求获取数据
      try {
        const { data: res } = await getEmployeesList(this.page, this.sezi)
        //  console.log(res.data.rows);
        const { header, data } = this.formatData(res.data.rows)
        // import('@/vendor/Export2Excel') 懒加载的方式导入一个模块(文件) 返回值是一个promise实例
        import('@/vendor/Export2Excel').then(excel => {
          //  excel 指的是模块对象,可以使用excel调用Export2Excel 文件中的函数或变量
          excel.export_json_to_excel({
            header,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (error) {
        console.log(error)
      }
      // 2. 将获取到的数据进行格式化,处理成生成excel文件需要的给是的数据(英文转为化中文)
      // - header 为 ['中文的表头]
      // - data  为 [['一条数据的值'],[]]
      // 3.调用admin中关键函数export_json_to_excel 生成excel文件
    },
    formatData(list) {
      // 1.根据数据对象的键根本映射关系,得到一个中文的键,放入到一个数据中 -- header
      // 2. 将每一个对象的值,存到一个数组中,所有的解构放入到一个大数组中 --data
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const one = list[0]
      // 如果list中有数组 才需要生成表头
      if (!one) return // 没有数据 直接终止
      const header = Object.keys(one).map(enkey => {
        return map[enkey]
      })
      // 2.生成data数据
      const data = list.map(item => {
        item.formOfEmployment = hireType[item.formOfEmployment]
        return Object.values(item)
      })
      return { header, data }
    },

    // 删除员工
    doDel(id) {
      this.$confirm('是否删除该员工?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await delEmployee(id)
          // 重新渲染
          // 优化删除
          if (this.list.length === 1) {
            this.page--
            if (this.page === 0) {
              this.page = 1
            }
          }
          this.loadEmployeesList()
        } catch (error) {
          console.log(error)
        }
      })
    },
    // 重置表单
    hResetFrom() {
      this.$refs.ref.doReset()
    },
    hSuccess() {
      // 关闭弹窗
      this.showDialog = false
      // 重新渲染
      // 实现新增优化,新增后跳转到新增内容页面
      this.total++
      const maxPage = Math.ceil(this.total / this.sezi)
      this.page = maxPage
      this.loadEmployeesList()
    },
    // 实现控制每页数据条数
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.page = 1
      this.sezi = val
      this.loadEmployeesList()
    },
    // 实现翻页功能
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeesList()
    },
    // 格式化聘用形式对的函数
    formOfEmploymentFormt(data) {
      // return EmployeesEnum.hireType.find(item => item.id === data).value
      return hireType[data] || '未知'
    },
    // 获取员工列表
    async loadEmployeesList() {
      const { data: res } = await getEmployeesList(this.page, this.sezi)
      // console.log('res', res)
      this.list = res.data.rows
      this.total = res.data.total
    }
  }
}
</script>
